<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Product extends Backend
{
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Product');
    }
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(['id', 'name'], false);
            $total = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            foreach($list as &$item){
                $item['image'] = explode(',',$item['image']);
//                $cate_ids = explode(",", $item['cate_id']);
                $cate_ids = model('ProductCate')->where('pro_id', $item['id'])->group('cate_id')->column('cate_id');
                $cate_arr = [];
                foreach($cate_ids as $v){
                    $cate = model('StoreCate')->where('id',$v)->find();
                    array_push($cate_arr,$cate['name']);
                }
                $item['cate'] = implode(" | ",$cate_arr);

                $store_ids = model('ProductStore')->where('pro_id',$item['id'])->column('store_id');
                $store_arr = [];
                foreach($store_ids as $v){
                    $cate = model('Store')->where('id',$v)->find();
                    array_push($store_arr,$cate['name']);
                }
                $item['store'] = implode(" | ",$store_arr);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    $validate = 'Product.add';
                    $cate_ids = $params['cate_id'];
                    $store_id = $params['store_id'];
                    $this->model->validateFailException(true)->validate($validate);
                    $params['cate_id'] = implode(",",$params['cate_id']);
                    $result = $this->model->allowField(true)->save($params);
                    model('ProductStore')->create(['pro_id'=>$this->model->getData('id'),'store_id'=>$store_id]);

                    foreach($cate_ids as $item){
                        model('ProductCate')->create(['pro_id'=>$this->model->getData('id'),'cate_id'=>$item]);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            $this->assign("cateList",$this->getCateList());
        }
        return $this->view->fetch();
    }
    public function edit($ids = '')
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    $validate = 'Product.edit';
                    $cate_ids = $params['cate_id'];
                    $store_id = $params['store_id'];

                    $row->validateFailException(true)->validate($validate);
                    $params['cate_id'] = implode(",",$params['cate_id']);
                    $result = $row->allowField(true)->save($params);

                    model('ProductStore')->where('pro_id',$ids)->delete();
                    model('ProductStore')->create(['pro_id'=>$ids,'store_id'=>$store_id]);

                    model('ProductCate')->where('pro_id',$ids)->delete();
                    foreach($cate_ids as $v){
                        model('ProductCate')->create(['pro_id'=>$ids,'cate_id'=>$v]);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign("cateList",$this->getCateList());
        $cates = explode(",",$row['cate_id']);
        $this->view->assign("cates", $cates);

        $store_id = model('ProductStore')->where('pro_id',$ids)->column('store_id');
        $this->view->assign("store_id", implode(",",$store_id));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = '')
    {
        parent::del($ids);
    }

    protected function getCateList()
    {
        $list = model('StoreCate')->order('weigh desc, id desc')->column('id,name');
        return $list;
    }

    public function storeSelect(){
        $keyword = $this->request->param('name');
        $where = [];
        if($this->request->request("keyValue")){
            $ids = explode(",",$this->request->request("keyValue"));
            $where['id'] = ['in',$ids];
        }
        if($keyword){
            $where['name'] = ['like',"%$keyword%"];
        }
        $store = model('Store')->where($where)->order('id desc')->field(['id', 'name'])->select();
        foreach($store as $item){
            $item['name'] = $item['name']."(id: ".$item['id'].")";
        }
        return json(['list' => $store, 'total' => count($store)]);
    }

}
